library gif_inspector;

import 'dart:ui' as ui;
import 'dart:typed_data';

import 'package:gif_inspector/bean/frame_bean.dart';
import 'package:gif_inspector/util/log/log.dart';


class GifInspector {

  GifInspector._();

  static Future<List<FrameBean>> readGif(Uint8List data) async{
    List<FrameBean> frames = [];
    ui.Codec codec = await ui.instantiateImageCodec(data);
    int frameCount = codec.frameCount;
    Log.log('frameCount $frameCount');
    for(int i = 0; i < frameCount; i++){
      /// handle each frame
      try{
        FrameBean frameBean = FrameBean.empty();
        ui.FrameInfo frameInfo = await codec.getNextFrame();
        Duration duration = frameInfo.duration;
        Log.log('$i frame duration ${duration.inMilliseconds}ms');
        frameBean.duration = duration;
        ByteData? byteData = await frameInfo.image.toByteData(
            format: ui.ImageByteFormat.png
        );
        if(byteData != null){
          frameBean.data = Uint8List.view(byteData.buffer);
          frames.add(frameBean);
        }
      }catch(e){
        Log.log('handle $i frame error: $e');
      }
    }
    return frames;
  }
}
